package com.xneure.utils.upload;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import com.xneure.utils.StrUtil;

/**
 * <p>
 * 上传数据分解处理器
 * </p>
 * <p>
 * Copyright: 版权所有<br>
 *
 * @author zhangjun
 * @version 2018年9月17日
 */
public class Part{
	private final byte[] head = {'\r','\n','\r','\n'};
	private byte[] partValue;
	private String contentDisposition;
	private String partName;
	private String contentType;

	public Part(byte[] fileData){
		int i = splitHead(fileData);
		headInfo(new String(Arrays.copyOfRange(fileData,0,i - 2)));
		this.partValue = Arrays.copyOfRange(fileData,i,fileData.length);
	}

	/**
	 * 定位文件头信息位置
	 * 
	 * @param fileData
	 * @return int
	 */
	private int splitHead(byte[] fileData){
		int boundaryLength = head.length - 1;
		next:
		for(int i = 0;i < fileData.length;i++){
			if(fileData[i] == head[0] && fileData[boundaryLength + i] == head[boundaryLength]){
				for(int l = 1;l < boundaryLength;l++){
					if(fileData[i + l] != head[boundaryLength - (boundaryLength - l)]){
						continue next;
					}
				}
				return i + boundaryLength + 1;
			}
			if(i >= fileData.length - boundaryLength){
				break;
			}
		}
		return -1;
	}

	/**
	 * 分解处理上传数据头信息
	 * 
	 * @param head part头信息
	 */
	protected void headInfo(String head){
		String[] tmp = StrUtil.strToArray(head);
		for(String s:tmp){
			int delimiter = s.indexOf(":");
			String content = s.substring(0,delimiter);
			String[] strVal = StrUtil.strToArray(s.substring(delimiter + 1),";");
			for(String var:strVal){
				if(var.contains("=")){
					String[] tmpVar = var.split("=",2);
					partAnalyze(content,tmpVar[0],tmpVar[1]);
				}else{
					partAnalyze(content,null,var);
				}
			}
		}
	}

	/**
	 * 处理上次part头信息
	 * 
	 * @param contentKey part参数名
	 * @param key 多参数时的参数名
	 * @param value 值
	 */
	protected void partAnalyze(String contentKey,String key,String value){
		if(contentKey.contains("Content-Disposition")){
			if(null == key){
				contentDisposition = value;
			}else if(key.contains("name")){
				partName = value;
			}
		}else if(contentKey.contains("Content-Type")){
			if(null == key){
				contentType = value;
			}
		}else if(contentKey.contains("Content-Transfer-Encoding")){
			if(null == key){
				contentType = value;
			}
		}
	}

	public String getContentDisposition(){
		return contentDisposition;
	}

	public String getPartName(){
		return partName;
	}

	public String getContentType(){
		return contentType;
	}

	/**
	 * 获取原始上传数据
	 * 
	 * @return byte[]
	 */
	public byte[] getPartValue(){
		return partValue;
	}

	/**
	 * 使用默认字符集转换成字符串
	 */
	public String getValue(){
		return new String(partValue);
	}

	/**
	 * 指定转换数据字集
	 */
	public String getValue(String charset){
		try{
			return new String(partValue,charset);
		}catch(UnsupportedEncodingException e){
			e.printStackTrace();
			return null;
		}
	}
}
